//
//  SDNestedTableViewController.m
//  SDNestedTablesExample
//
//  Created by Daniele De Matteis on 21/05/2012.
//  Copyright (c) 2012 Daniele De Matteis. All rights reserved.
//

#import "SDNestedTableViewController.h"
#import <QuartzCore/QuartzCore.h>
#import "MainViewController.h"
@interface SDNestedTableViewController ()

@end

@implementation SDNestedTableViewController

@synthesize mainItemsAmt, subItemsAmt, groupCell;
@synthesize delegate;

- (id) init
{
    if (self = [super init])
    {
    }
    return self;
}

- (id) initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    if((self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]))
    {
        self.delegate = self;
    }
    
    return self;
}

#pragma mark - To be implemented in sublclasses

- (NSInteger)mainTable:(UITableView *)mainTable numberOfItemsInSection:(NSInteger)section
{
//    NSLog(@"\n Oops! You didn't specify the amount of Items in the Main tableview \n Please implement \"%@\" in your SDNestedTables subclass.", NSStringFromSelector(_cmd));
    return 0;
}

- (NSInteger)mainTable:(UITableView *)mainTable numberOfSubItemsforItem:(SDGroupCell *)item atIndexPath:(NSIndexPath *)indexPath
{
//    NSLog(@"\n Oops! You didn't specify the amount of Sub Items for this Main Item \n Please implement \"%@\" in your SDNestedTables subclass.", NSStringFromSelector(_cmd));
    return 0;
}

- (SDGroupCell *)mainTable:(UITableView *)mainTable setItem:(SDGroupCell *)item forRowAtIndexPath:(NSIndexPath *)indexPath 
{
    if (indexPath.row == 0)
    {
//        NSLog(@"\n Oops! Item cells in the Main tableview are not configured \n Please implement \"%@\" in your SDNestedTables subclass.", NSStringFromSelector(_cmd));
    }
    return item;
}

- (SDSubCell *)item:(SDGroupCell *)item setSubItem:(SDSubCell *)subItem forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == 0)
    {
//        NSLog(@"\n Oops! Sub Items for this Item are not configured \n Please implement \"%@\" in your SDNestedTables subclass.", NSStringFromSelector(_cmd));
    }
    return subItem;
}

- (void)expandingItem:(SDGroupCell *)item withIndexPath:(NSIndexPath *)indexPath
{
    
}

- (void)collapsingItem:(SDGroupCell *)item withIndexPath:(NSIndexPath *)indexPath 
{

}
    
// Optional method to implement. Will be called when creating a new main cell to return the nib name you want to use

- (NSString *) nibNameForMainCell
{
    return @"SDGroupCell";
}

#pragma mark - Delegate methods

- (void) mainTable:(UITableView *)mainTable itemDidChange:(SDGroupCell *)item
{
//    NSLog(@"\n Oops! You didn't specify a behavior for this Item \n Please implement \"%@\" in your SDNestedTables subclass.", NSStringFromSelector(_cmd));
}

- (void) item:(SDGroupCell *)item subItemDidChange:(SDSubCell *)subItem
{
//    NSLog(@"\n Oops! You didn't specify a behavior for this Sub Item \n Please implement \"%@\" in your SDNestedTables subclass.", NSStringFromSelector(_cmd));
}

- (void) mainItemDidChange: (SDGroupCell *)item forTap:(BOOL)tapped
{
    if(delegate != nil && [delegate respondsToSelector:@selector(mainTable:itemDidChange:)] )
    {
        [delegate performSelector:@selector(mainTable:itemDidChange:) withObject:self.tableView withObject:item];
    }
}

- (void) mainItem:(SDGroupCell *)item subItemDidChange: (SDSubCell *)subItem forTap:(BOOL)tapped
{
    if(delegate != nil && [delegate respondsToSelector:@selector(item:subItemDidChange:)] )
    {
        [delegate performSelector:@selector(item:subItemDidChange:) withObject:item withObject:subItem];
    }
}

#pragma mark - Class lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    lastIndexPath=[NSIndexPath indexPathForRow:0 inSection:0];
    
    subItemsAmt = [[NSMutableDictionary alloc] initWithDictionary:nil];
	expandedIndexes = [[NSMutableDictionary alloc] init];
    
    self.tableView.backgroundColor = [UIColor clearColor];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
  
    [self.view setBackgroundColor:[UIColor colorWithPatternImage:[UIImage imageNamed:@"background.png"]]];
    
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 1)];
    view.backgroundColor = [UIColor grayColor];
    view.alpha = 0.8;
    self.tableView.tableHeaderView = view;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
}

#pragma mark - TableView delegation
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    mainItemsAmt = [self mainTable:tableView numberOfItemsInSection:section];
    return mainItemsAmt;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    SDGroupCell *cell = [tableView dequeueReusableCellWithIdentifier:@"GroupCell"];
    if (cell == nil) {
        cell = [[[NSBundle mainBundle] loadNibNamed:@"SDGroupCell" owner:self options:nil] lastObject];
    }
    [cell setParentTable: self];
    [cell setCellIndex:indexPath.row];
    
    cell = [self mainTable:tableView setItem:cell forRowAtIndexPath:indexPath];
    
    NSNumber *index=[[NSNumber alloc] initWithInt:indexPath.row];
    int amtcount=[self mainTable:tableView numberOfSubItemsforItem:cell atIndexPath:indexPath];
    NSNumber *amt =[[NSNumber alloc] initWithInt:amtcount];
    subItemsAmt[index] = amt;
    [cell setSubCellsAmt: [subItemsAmt[index] intValue]];
    
    BOOL isExpanded = [expandedIndexes[index] boolValue];
    cell.isExpanded = isExpanded;
//    [cell initView:isExpanded];
    [cell.subTable reloadData];
    
    [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
    [cell setAccessoryType:UITableViewCellAccessoryNone];
    return cell;
}

- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    NSNumber *index=[[NSNumber alloc] initWithInt:indexPath.row];
    int amt = [subItemsAmt[index] intValue];
    BOOL isExpanded = [expandedIndexes[index] boolValue];
    
    if (isExpanded && amt > 0) {
        if ([self isKindOfClass:[MainViewController class]]) {
            return [SDGroupCell getHeight] + [SDGroupCell getsubCellHeight1]*amt + 1;
        }else{
            return [SDGroupCell getHeight] + [SDGroupCell getsubCellHeight2]*amt + 1;
        }
        
    }
    return [SDGroupCell getHeight];
}

- (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [self.view endEditing:YES];
	[tableView deselectRowAtIndexPath:indexPath animated:YES];
    [self toggleSubCellWithIndexPath:indexPath];
}

#pragma mark - Nested Tables events
- (void) groupCell:(SDGroupCell *)cell didSelectSubCell:(SDSubCell *)subCell withIndexPath:(NSIndexPath *)indexPath andWithTap:(BOOL)tapped {
    NSIndexPath *groupCellIndexPath = [self.tableView indexPathForCell:cell];
    if (groupCellIndexPath != nil && indexPath != nil) {
        [self mainItem:cell subItemDidChange:subCell forTap:tapped];
    }
}

- (void)collapsableButtonTapped:(UIControl *)button withEvent:(UIEvent *)event {
    UITableView *tableView = self.tableView;
    NSIndexPath * indexPath = [tableView indexPathForRowAtPoint:[[[event touchesForView: button] anyObject] locationInView: tableView]];
    if ( indexPath == nil )
        return;
    
    [self toggleSubCellWithIndexPath:indexPath];
}

- (void)toggleSubCellWithIndexPath:(NSIndexPath *)indexPath {
    NSNumber *index=[[NSNumber alloc] initWithInt:indexPath.row];
	BOOL isExpanded = ![expandedIndexes[index] boolValue];
	NSNumber *expandedIndex = [[NSNumber alloc] initWithBool:isExpanded];
	expandedIndexes[index] = expandedIndex;

    UITableView *tableView = self.tableView;
    SDGroupCell *cell = (SDGroupCell *)[tableView cellForRowAtIndexPath:indexPath];
//    [cell initView:isExpanded];
    
    NSIndexPath *tempIndex;
    if (isExpanded) {
        for (int i=0; i<mainItemsAmt; i++) {
            if (i!=indexPath.row) {
                index=[[NSNumber alloc] initWithInt:i];
                isExpanded = [expandedIndexes[index] boolValue];
                if (isExpanded) {
                    isExpanded=!isExpanded;
                    expandedIndex = [[NSNumber alloc] initWithBool:isExpanded];
                    expandedIndexes[index] =expandedIndex;
                    tempIndex=[NSIndexPath indexPathForRow:i inSection:0];
                    cell = (SDGroupCell *)[tableView cellForRowAtIndexPath:tempIndex];
//                    [cell initView:isExpanded];
                }
            }
        }
    }

    [self.tableView beginUpdates];
    [self.tableView endUpdates];
}

@end
